<template>
  <div class="home">
    <!-- 轮播图 -->
    <div class="banner">
      <el-carousel height="300px" indicator-position="inside">
        <el-carousel-item v-for="item in banners" :key="item.id">
          <div class="banner-item" :style="{ backgroundImage: `url(${item.image})` }">
            <div class="banner-content">
              <h3>{{ item.title }}</h3>
              <p>{{ item.description }}</p>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" :class="{ 'no-sidebar': filters.category === '5' }">
      <!-- 左侧内容 -->
      <div class="content-left">
        <!-- 筛选和搜索 -->
        <div class="filters card">
          <div class="filter-row">
            <div class="filter-left">
              <el-select v-model="filters.sortBy" placeholder="排序方式">
                <el-option label="最新发布" value="latest" />
                <el-option label="最多点赞" value="likes" />
                <el-option label="最多评论" value="comments" />
              </el-select>
            </div>
            
            <div class="filter-right">
              <el-input
                v-model="filters.keyword"
                placeholder="搜索帖子..."
                class="search-input"
                @keyup.enter="searchPosts"
              >
                <template #append>
                  <el-button icon="Search" @click="searchPosts" />
                </template>
              </el-input>
            </div>
          </div>
        </div>

        <!-- 帖子列表 -->
        <div class="posts">
          <div class="posts-header">
            <h3>{{ currentCategoryName }}</h3>
            <el-button type="text" @click="refreshPosts">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>

      <el-skeleton :loading="loading" animated>
        <template #template>
          <div v-for="n in 3" :key="n" class="skeleton-item card">
            <el-skeleton-item variant="circle" style="width: 40px; height: 40px" />
            <div style="margin-left: 16px; flex: 1">
              <el-skeleton-item variant="text" style="width: 30%" />
              <el-skeleton-item variant="text" style="width: 80%; margin-top: 8px" />
              <el-skeleton-item variant="text" style="width: 60%; margin-top: 8px" />
            </div>
          </div>
        </template>
        
        <template #default>
          <div v-if="posts.length === 0" class="empty-state">
            <el-empty description="暂无帖子" />
          </div>
          
          <div v-else class="post-list">
            <div 
              v-for="post in posts" 
              :key="post.id" 
              class="post-item card post-item"
              @click="goToPost(post.id)"
            >
              <!-- 用户信息 -->
              <div class="post-header">
                <div class="user-info">
                  <el-avatar :size="40" :src="post.user.avatar">
                    {{ post.user.username.charAt(0) }}
                  </el-avatar>
                  <div class="user-details">
                    <div class="username">{{ post.user.username }}</div>
                    <div class="post-time">{{ formatTime(post.createTime) }}</div>
                  </div>
                </div>
                
                <el-tag v-if="post.category" size="small" type="info">
                  {{ post.category.name }}
                </el-tag>
              </div>

              <!-- 帖子内容 -->
              <div class="post-content">
                <h4 class="post-title">{{ post.title }}</h4>
                <p class="post-excerpt">{{ post.content }}</p>
                
                <!-- 图片展示 -->
                <div v-if="post.images && post.images.length > 0" class="post-images">
                  <el-image
                    v-for="(image, index) in post.images.slice(0, 3)"
                    :key="index"
                    :src="image"
                    class="post-image"
                    fit="cover"
                    :preview-src-list="post.images"
                    :initial-index="index"
                  />
                  <div v-if="post.images.length > 3" class="more-images">
                    +{{ post.images.length - 3 }}
                  </div>
                </div>
              </div>

              <!-- 帖子操作 -->
              <div class="post-actions">
                <div class="action-buttons">
                  <el-button 
                    text 
                    :type="post.isLiked ? 'danger' : 'info'"
                    @click.stop="toggleLike(post)"
                  >
                    <el-icon><Heart /></el-icon>
                    {{ post.likesCount || 0 }}
                  </el-button>
                  
                  <el-button text type="info">
                    <el-icon><ChatLineRound /></el-icon>
                    {{ post.commentsCount || 0 }}
                  </el-button>
                  
                  <el-button text type="info">
                    <el-icon><View /></el-icon>
                    {{ post.viewsCount || 0 }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-skeleton>

          <!-- 分页 -->
          <div v-if="total > 0" class="pagination">
            <el-pagination
              v-model:current-page="pagination.page"
              v-model:page-size="pagination.size"
              :page-sizes="[10, 20, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      
      <!-- 右侧热度榜 - 失物招领和二手交易不显示热度榜 -->
      <div class="content-right" v-if="filters.category !== '5'">
        <HotRankingSidebar :category-id="filters.category" />
      </div>
    </div>
    
    <!-- 发布帖子按钮 -->
    <PostFab />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getPostList } from '@/api/post'
import { likePost, unlikePost } from '@/api/post'
import dayjs from 'dayjs'
import HotRankingSidebar from '@/components/HotRankingSidebar.vue'
import PostFab from '@/components/PostFab.vue'

// 数据
const loading = ref(false)
const posts = ref([])
const total = ref(0)
const categories = ref([
  { id: 1, name: '学习交流' },
  { id: 2, name: '生活分享' },
  { id: 3, name: '求助提问' },
  { id: 4, name: '社团活动' },
  { id: 5, name: '二手交易' }
])

const banners = ref([
  {
    id: 1,
    title: '欢迎来到校园墙',
    description: '分享你的校园生活，发现更多精彩',
    image: 'https://picsum.photos/1200/300?random=1'
  },
  {
    id: 2,
    title: '学习交流',
    description: '与同学们一起学习进步',
    image: 'https://picsum.photos/1200/300?random=2'
  },
  {
    id: 3,
    title: '社团活动',
    description: '丰富多彩的校园活动等你参与',
    image: 'https://picsum.photos/1200/300?random=3'
  }
])

// 筛选条件
const filters = reactive({
  category: '',
  sortBy: 'latest',
  keyword: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10
})

// 方法
const router = useRouter()
const route = useRoute()

// 当前分类名称
const currentCategoryName = computed(() => {
  const categoryId = route.query.category
  if (!categoryId) return '全部帖子'
  const category = categories.value.find(c => c.id === parseInt(categoryId))
  return category ? category.name : '全部帖子'
})

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filters
    }
    const response = await getPostList(params)
    posts.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    console.error('获取帖子列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索帖子
const searchPosts = () => {
  pagination.page = 1
  fetchPosts()
}

// 刷新帖子
const refreshPosts = () => {
  fetchPosts()
}

// 跳转到帖子详情
const goToPost = (id) => {
  router.push(`/post/${id}`)
}

// 切换点赞状态
const toggleLike = async (post) => {
  try {
    if (post.isLiked) {
      await unlikePost(post.id)
      post.likesCount--
      post.isLiked = false
    } else {
      await likePost(post.id)
      post.likesCount++
      post.isLiked = true
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
  }
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchPosts()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchPosts()
}

// 监听筛选条件变化
watch(filters, () => {
  pagination.page = 1
  fetchPosts()
}, { deep: true })

// 初始化
onMounted(() => {
  // 从 URL 参数中读取分类
  const categoryId = route.query.category
  if (categoryId) {
    filters.category = categoryId
  }
  fetchPosts()
})

// 监听路由参数变化
watch(() => route.query.category, (newCategory) => {
  filters.category = newCategory || ''
  pagination.page = 1
  fetchPosts()
})
</script>

<style scoped>
.banner {
  margin-bottom: 32px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.banner-item {
  height: 300px;
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.banner-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.8) 0%, rgba(118, 75, 162, 0.8) 100%);
}

.banner-content {
  position: relative;
  z-index: 1;
  text-align: center;
  color: white;
  max-width: 600px;
  padding: 0 20px;
}

.banner-content h3 {
  font-size: 48px;
  font-weight: 700;
  margin-bottom: 16px;
  letter-spacing: -1px;
  text-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.banner-content p {
  font-size: 20px;
  opacity: 0.95;
  font-weight: 400;
  line-height: 1.6;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

/* 主要内容区域布局 */
.main-content {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.content-left {
  flex: 1;
  min-width: 0;
}

.content-right {
  width: 320px;
  flex-shrink: 0;
}

/* 当没有侧边栏时的布局调整 */
.main-content.no-sidebar {
  gap: 0;
}

.main-content.no-sidebar .content-left {
  max-width: 100%;
}

.filters {
  margin-bottom: 32px;
  background: rgba(255, 255, 255, 0.98);
  border: 1px solid rgba(226, 232, 240, 0.6);
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-left {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.filter-left .el-select {
  width: 160px;
}

.search-input {
  width: 320px;
}

.posts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.posts-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: -0.5px;
}

.posts-header .el-button {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  border: none;
}

.skeleton-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 24px;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-item {
  cursor: pointer;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.98);
  border: 1px solid rgba(226, 232, 240, 0.6);
  position: relative;
  overflow: hidden;
}

.post-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transform: scaleY(0);
  transition: transform 0.3s ease;
}

.post-item:hover::before {
  transform: scaleY(1);
}

.post-item:hover {
  transform: translateY(-6px);
  box-shadow: 
    0 20px 40px rgba(0, 0, 0, 0.1),
    0 8px 16px rgba(0, 0, 0, 0.06);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.username {
  font-weight: 600;
  color: #1e293b;
  font-size: 15px;
}

.post-time {
  font-size: 13px;
  color: #64748b;
  font-weight: 500;
}

.post-content {
  margin-bottom: 20px;
}

.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 12px;
  line-height: 1.4;
  letter-spacing: -0.3px;
}

.post-excerpt {
  color: #475569;
  line-height: 1.7;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  font-size: 15px;
}

.post-images {
  display: flex;
  gap: 12px;
  position: relative;
}

.post-image {
  width: 90px;
  height: 90px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.more-images {
  width: 90px;
  height: 90px;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.5));
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  backdrop-filter: blur(10px);
}

.post-actions {
  border-top: 1px solid rgba(0, 0, 0, 0.06);
  padding-top: 16px;
}

.action-buttons {
  display: flex;
  gap: 32px;
}

.action-buttons .el-button {
  border: none;
  background: transparent;
  color: #64748b;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.action-buttons .el-button:hover {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  transform: translateY(-1px);
}

.action-buttons .el-button--danger {
  color: #ef4444;
}

.action-buttons .el-button--danger:hover {
  background: rgba(239, 68, 68, 0.1);
  color: #dc2626;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 20px;
  border: 1px solid rgba(226, 232, 240, 0.6);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-right {
    display: none;
  }
  
  .main-content {
    gap: 0;
  }
}

@media (max-width: 768px) {
  .banner-content h3 {
    font-size: 32px;
  }
  
  .banner-content p {
    font-size: 16px;
  }
  
  .filter-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-left {
    width: 100%;
    justify-content: space-between;
  }
  
  .search-input {
    width: 100%;
  }
  
  .post-images {
    gap: 8px;
  }
  
  .post-image,
  .more-images {
    width: 70px;
    height: 70px;
  }
  
  .action-buttons {
    gap: 20px;
  }
}
</style>